package com.muyan.sys.common.utils.snow;

import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.IdUtil;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SnowIds {
    private static final long WORKER_ID_BITS = 10L;

    /**
     * IP地址第三段编号最大个数（32*32/256=4）
     */
    private static final int MAX_IP_THIRD_SECTION_COUNT = 4;
    /**
     * IPv4 正则表达式验证规则
     */
    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    /**
     * 雪花算法 workerId
     */
    public static final String KEY_WORKER_ID = "workerId";
    /**
     * 雪花算法 datacenterId
     */
    public static final String KEY_DATACENTER_ID = "datacenterId";
    public static Long getId(){
        Map<String, Integer> map= getWorkerIdAndDatacenterId();
        return  IdUtil.getSnowflake(map.get(KEY_WORKER_ID), map.get(KEY_DATACENTER_ID)).nextId();
    }
    /**
     * 获取雪花算法 workerId 和 datacenterId（IP地址第三、四段都有变化）
     *
     * @param ip IP地址
     *
     * @return {@link Map<String, Integer>} workerId 和 datacenterId
     * @author Supreme_Sir
     * @date 2024/6/11 17:40
     */
    public static Map<String, Integer> getWorkerIdAndDatacenterId() {


        String  ip = null;
        try {

            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

        // 切分 IP 地址，获取第三段和第四段内容
        String[] split = ip.split("\\.");
        int thirdSectionNum = Integer.parseInt(split[2]);
        int fourthSectionNum =  Integer.parseInt(split[3]);

        // 计算 workerId 和 datacenterId
        int loopCount = thirdSectionNum % MAX_IP_THIRD_SECTION_COUNT;
        int workerId = (fourthSectionNum / 32) + (loopCount * 8);
        int datacenterId = fourthSectionNum % 32;

        // 返回结果
        Map<String, Integer> result = new HashMap<>();
        result.put(KEY_WORKER_ID, workerId);
        result.put(KEY_DATACENTER_ID, datacenterId);

        return result;
    }

    /**
     * 验证给定的字符串是否为有效的IPv4地址。
     *
     * @param ip 要验证的IP地址字符串
     * @return 如果是有效的IPv4地址则返回true，否则返回false
     */
    public static boolean isValidIPv4(String ip) {
        Matcher matcher = IPV4_PATTERN.matcher(ip);
        return matcher.matches();
    }

    public static void main(String[] args) {
        //System.out.println(String.valueOf(getSnowflakeId()).length());
    }

    /**
     * <p>
     * 数据标识id部分
     * </p>
     */
    protected static long getWorkerId() {
        long id = 0L;
        long maxDatacenterId= -1L ^ (-1L << WORKER_ID_BITS);
        try {
            InetAddress ip = InetAddress.getLocalHost();
            if(ip!=null){
                String tempIP = "127.0.0.1";
                try {
                    tempIP = InetAddress.getLocalHost().getHostAddress();
                    tempIP=   tempIP.substring(tempIP.lastIndexOf(".")+1);
                    return Long.valueOf(tempIP);
                } catch (UnknownHostException e1) {
                    // ignore
                }
            }
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {

                byte[] mac = network.getHardwareAddress();
                id = ((0x000000FF & (long) mac[mac.length - 1])
                        | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                id = id % (maxDatacenterId + 1);
            }

        } catch (Exception e) {

            id = 1L;
        }
        return id;
    }
}

